<?php
// 应用公共文件

/**
 * 字节数Byte转换为KB、MB、GB、TB
 * @param int $size
 * @return string
 */
function xn_file_size($size){
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $units[$i];
}

/**
 * 驼峰命名转下划线命名
 * @param $camelCaps
 * @param string $separator
 * @return string
 */
function xn_uncamelize($camelCaps,$separator='_')
{
    return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
}

/**
 * 密码加密函数
 * @param $password
 * @return string
 */
function xn_encrypt($password)
{
    $salt = 'xiaoniu_admin';
    return md5(md5($password.$salt));
}

/**
 * 管理员操作日志
 * @param $remark
 */
function xn_add_admin_log($remark)
{
    $data = [
        'admin_id' => session('admin_auth.id'),
        'url' => request()->url(true),
        'ip' => request()->ip(),
        'remark' => $remark,
        'method' =>request()->method(),
        'param' => json_encode(request()->param()),
        'create_time' => time()
    ];
    \app\common\model\AdminLog::insert($data);
}

/**
 * 获取自定义config/cfg目录下的配置
 * 用法： xn_cfg('base') 或 xn_cfg('base.website') 不支持无限极
 * @param string|null $name
 * @param string|null $default
 * @param string|null $path
 * @return array|string
 */
function xn_cfg($name, $default='', $path='cfg')
{
    if (false === strpos($name, '.')) {
        $name = strtolower($name);
        $config  = \think\facade\Config::load($path.'/'.$name, $name);
        return $config ?? [];
    }
    $name_arr    = explode('.', $name);
    $name_arr[0] = strtolower($name_arr[0]);
    $filename = $name_arr[0];
    $config  = \think\facade\Config::load($path.'/'.$filename, $filename);
    return $config[$name_arr[1]] ?? $default;
}

/**
 * 根目录物理路径
 * @return string
 */
function xn_root()
{
    return app()->getRootPath() . 'public';
}

/**
 * 构建图片上传HTML 单图
 * @param string $value
 * @param string $file_name
 * @param null $water 是否添加水印 null-系统配置设定 1-添加水印 0-不添加水印
 * @param null $thumb 生成缩略图，传入宽高，用英文逗号隔开，如：200,200（仅对本地存储方式生效，七牛、oss存储方式建议使用服务商提供的图片接口）
 * @return string
 */
function xn_upload_one($value,$file_name,$water=null,$thumb=null)
{
$html=<<<php
    <div class="xn-upload-box">
        <div class="t layui-col-md12 layui-col-space10">
            <input type="hidden" name="{$file_name}" class="layui-input xn-images" value="{$value}">
            <div class="layui-col-md4">
                <div type="button" class="layui-btn webuploader-container" id="{$file_name}" data-water="{$water}" data-thumb="{$thumb}" style="width: 113px;"><i class="layui-icon layui-icon-picture"></i>上传图片</div>
                <div type="button" class="layui-btn chooseImage" data-num="1"><i class="layui-icon layui-icon-table"></i>选择图片</div>
            </div>
        </div>
        <ul class="upload-ul clearfix">
            <span class="imagelist"></span>
        </ul>
        <script>$('#{$file_name}').uploadOne();</script>
    </div>
php;
    return $html;
}

/**
 * 构建图片上传HTML 多图
 * @param string $value
 * @param string $file_name
 * @param null $water 是否添加水印 null-系统配置设定 1-添加水印 0-不添加水印
 * @param null $thumb 生成缩略图，传入宽高，用英文逗号隔开，如：200,200（仅对本地存储方式生效，七牛、oss存储方式建议使用服务商提供的图片接口）
 * @return string
 */
function xn_upload_multi($value,$file_name,$water=null,$thumb=null)
{
    $html=<<<php
    <div class="xn-upload-box">
        <div class="t layui-col-md12 layui-col-space10">
            <div class="layui-col-md8">
                <input type="text" name="{$file_name}" class="layui-input xn-images" value="{$value}">
            </div>
            <div class="layui-col-md4">
                <div type="button" class="layui-btn webuploader-container" id="{$file_name}" data-water="{$water}" data-thumb="{$thumb}" style="width: 113px;"><i class="layui-icon layui-icon-picture"></i>上传图片</div>
                <div type="button" class="layui-btn chooseImage"><i class="layui-icon layui-icon-table"></i>选择图片</div>
            </div>
        </div>
        <ul class="upload-ul clearfix">
            <span class="imagelist"></span>
        </ul>
        <script>$('#{$file_name}').upload();</script>
    </div>
php;
    return $html;
}

/**
 * 格式化标签，将空格、中文逗号替换成英文半角分号
 * @param $tags
 * @return string
 */
function xn_format_tags($tags)
{
    $tags = trim($tags);
    $tags = str_replace(' ',',',str_replace('，',',',$tags));
    $arr = explode(',',$tags);
    $data = [];
    foreach ($arr as $v) {
        if( $v!='' ) {
            $data[] = $v;
        }
    }
    return implode(',',$data);
}

/**
 * 生成全局唯一标识符
 * @param bool $trim
 * @return string
 */
function xn_create_guid()
{
    $charid = strtoupper(md5(uniqid(mt_rand(), true)));
    $hyphen = chr(45);// "-"
    $uuid = chr(123)// "{"
        .substr($charid, 0, 8).$hyphen
        .substr($charid, 8, 4).$hyphen
        .substr($charid,12, 4).$hyphen
        .substr($charid,16, 4).$hyphen
        .substr($charid,20,12)
        .chr(125);// "}"
    return $uuid;
}

//curl
function http_request($url, $header = null, $data = null){
    $curl = curl_init();
    if(!empty($header)){
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_HEADER, 0);//返回response头部信息
    }
 
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_HTTPGET, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS,http_build_query($data));
    }
 
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

//远程站点token
function site_token(){
    $date = date('Y.m.d.H',time());
    $token = md5(md5($date.'xiexueyuan.com'));
    return $token;
}

//生成订单号
function xn_create_order_no() {
    $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
    $orderSn = $yCode[intval(date('Y')) - 2020] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
    return $orderSn;
}

//获取类型名称
function get_typename($id){
    $data = \think\facade\Db::name('data_type')->find($id);
    return $data['title'];
}

//获取类型ID
function get_typeid($title,$level){
    $data = \think\facade\Db::name('data_type')->where([
        'title' => $title,
        'level' => $level
    ])->find();
    return $data['id'];
}

//获取类型PID
function get_typepid($id){
    $data = \think\facade\Db::name('data_type')->find($id);
    return $data['pid'];
}

//获取素材位置名称
function get_position_name($id){
    $data = \think\facade\Db::name('data_content_chip_position')->find($id);
    return $data['title'];
}

//获取素材模板数据
function get_template_value($value){
    $str = '';
    $value = explode(',',$value);
    $data = \think\facade\Db::name('data_content_chip_position')->where('id','in',$value)->order('sort asc')->select();
    foreach($data as $v){
        $str .= $v['sort'].'.'.$v['title'].' ';
    }
    return $str;
}

//获取重复项目名称
function get_repeat_name($id){
    $str = '';
    $res = \think\facade\Db::name('data_project')->find($id);
    $str .= get_typename($res['parent_typeid']).' > '.get_typename($res['typeid']).' > '.$res['title'];
    return $str;
}

//获取类型名称
function get_site_typename($id){
    $data = \think\facade\Db::name('site_type')->find($id);
    return $data['title'];
}

//随机颜色
function randColor(){
    $colors = array();
    for($i = 0;$i<6;$i++){
        $colors[] = dechex(rand(0,15));
    }
    return implode('',$colors);
}

//获取企业信息接口
function apiGetCom($kw){
    $host = "https://cardnotwo.market.alicloudapi.com";
    $path = "/company";
    $method = "POST";
    $appcode = "83ebe6a6a8b54ff1b014bb6411ed38f9";
    $headers = array();
    array_push($headers, "Authorization:APPCODE " . $appcode);
    $querys = "com=".urlencode($kw);
    $bodys = "";
    $url = $host . $path . "?" . $querys;

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_FAILONERROR, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    if (1 == strpos("$".$host, "https://"))
    {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    $data = curl_exec($curl);
    curl_close($curl);
    return $data;
}

//栏目树
function formatTree($array, $pid = 0, $level = 1,$field = array('pid'=>'pid','id'=>'id','children'=>'children')){
    $arr = array();
    foreach ($array as &$v) {
      if ($v[$field['pid']] == $pid) {
        $v['level'] = $level;
        $tem = formatTree($array, $v[$field['id']],$v['level']+1,$field);
        //判断是否存在子数组
        $tem && $v[$field['children']] = $tem;
        $arr[] = $v;
      }
    }
    return $arr;
}

//只替换一次字符串
function str_replace_once($needle, $replace, $haystack) { 
    $pos = strpos($haystack, $needle); 
    if ($pos === false) { 
        return $haystack; 
    } 
    return substr_replace($haystack, $replace, $pos, strlen($needle)); 
} 

//连接远程数据库 返回站点信息
function connect($webid){
    $web = \think\facade\Db::name('site_web')->find($webid);
    $conparas = [
        'type'     => $web['db_type'],
        'hostname' => $web['db_hostname'],
        'database' => $web['db_database'],
        'username' => $web['db_username'],
        'password' => $web['db_password'],
        'hostport' => $web['db_hostport'],
        'prefix'   => $web['db_prefix'],
    ];
    foreach($conparas as $v){
        if(empty($v)){
            return null;
        }
    }
    $database_config = \think\facade\Config::get('database');
    $database_config['connections']['dynamic'] = $conparas;
    \think\facade\Config::set($database_config, 'database');
    return $web;
}

//判断账号是否存在
function is_site_username($webid,$username){
    if(empty($webid) || empty($username)){
        return null;
    }
    $web = connect($webid);
    if(empty($web)){
        return null;
    }
    switch ($web['cms_type']) {
        case 'destoon':
            $user = \think\facade\Db::connect('dynamic')->name('member')->field('userid')->where('username',$username)->find();
            if(!empty($user)){
                return true;
            }
        break;
        case 'eyoucms':
            # code...
        break;
        case 'dedecms':
            # code...
        break;
    }
}

//获取客户端IP
function getClientIp()
{
    if (getenv('HTTP_CLIENT_IP')) {
        $ip = getenv('HTTP_CLIENT_IP');
    }
    if (getenv('HTTP_X_REAL_IP')) {
        $ip = getenv('HTTP_X_REAL_IP');
    } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
        $ips = explode(',', $ip);
        $ip = $ips[0];
    } elseif (getenv('REMOTE_ADDR')) {
        $ip = getenv('REMOTE_ADDR');
    } else {
        $ip = '0.0.0.0';
    }
    return $ip;
}

//匹配标签
function matchTag($content,$table){
    $str = '';
    $matchData = \think\facade\Db::name($table)->field('id,alias')->select()->toArray();
    foreach($matchData as $v){
        $alias_arr = explode(',',$v['alias']);
        foreach($alias_arr as $alias){
            if(strpos($content,$alias) !== false){ 
                $str .= $v['id'].',';
                break;
            }
        }
    }
    $str = rtrim($str,',');
    return $str;
}

//获取用户名
function get_username($id){
    $data = \think\facade\Db::name('admin')->find($id);
    return $data['username'];
}

//获取公司项目
function get_com_project($company){
    $data = \think\facade\Db::name('data_project')->field('title')->where('company',$company)->select()->toArray();
    $str = '';
    foreach($data as $v){
        $str .= $v['title'].',';
    }
    $str = rtrim($str,',');
    return $str;
}

//获取属性
function getAttr($str){
    $attr = '';

    $matchData = \think\facade\Db::name('data_tag_attr')->field('title,alias')->select()->toArray();
    $attr .= matchAttr($str,$matchData);
    $matchData = \think\facade\Db::name('data_tag_crowd')->field('title,alias')->select()->toArray();
    $attr .= matchAttr($str,$matchData);
    $matchData = \think\facade\Db::name('data_tag_amount')->field('title,alias')->select()->toArray();
    $attr .= matchAttr($str,$matchData);
    $matchData = \think\facade\Db::name('data_tag_region')->field('title,alias')->select()->toArray();
    $attr .= matchAttr($str,$matchData);
    $matchData = \think\facade\Db::name('data_tag_operate')->field('title,alias')->select()->toArray();
    $attr .= matchAttr($str,$matchData);

    return rtrim($attr,',');
}

//匹配属性
function matchAttr(&$str,&$matchData){
    $attr = '';
    foreach($matchData as $v){
        $alias_arr = explode(',',$v['alias']);
        foreach($alias_arr as $alias){
            if(strpos($str,$alias) !== false){ 
                $attr .= $v['title'].',';
                break;
            }
        }
    }
    return $attr;
}

//获取门店数量
function get_shop_num($typeid,$project){
    $count = \think\facade\Db::name('data_project_shop')->where([
        'typeid' => ['eq', $typeid],
        'project' => ['eq', $project]
    ])->count();
    return $count;
}

//违规词检测
function checkViolation(&$content){
    $data = xn_cfg('violation.words');
    $arr = explode('、',$data);
    $res = '';
    foreach($arr as $v){
        if(strpos($content, $v) !== false){
            $res .= $v.',';
        }
    }
    $res = rtrim($res,',');
    return $res;
}

//违规词标红
function markViolation(&$content){
    $data = xn_cfg('violation.words');
    $arr = explode('、',$data);
    foreach($arr as $v){
        $content = str_replace($v,'<span style="color:red;">'.$v.'</span>',$content);
    }
    return $content;
}

/**
 * 计算两点之间的距离
 * @param $lng1 经度1
 * @param $lat1 纬度1
 * @param $lng2 经度2
 * @param $lat2 纬度2
 * @param int $unit m，km
 * @param int $decimal 位数
 * @return float
 */
function getDistance($lng1, $lat1, $lng2, $lat2, $unit = 2, $decimal = 2)
{

    $EARTH_RADIUS = 6370.996; // 地球半径系数
    $PI           = 3.1415926535898;

    $radLat1 = $lat1 * $PI / 180.0;
    $radLat2 = $lat2 * $PI / 180.0;

    $radLng1 = $lng1 * $PI / 180.0;
    $radLng2 = $lng2 * $PI / 180.0;

    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;

    $distance = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
    $distance = $distance * $EARTH_RADIUS * 1000;

    if ($unit === 2) {
        $distance /= 1000;
    }

    return round($distance, $decimal);
}